package com.zlyx.easy.security.defaults.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;

import com.zlyx.easy.security.authentication.service.IClientDetailsService;

/**
 * <p>
 * 默认客户端查询接口实现
 * </p>
 *
 * @author 赵光
 * @version v1.0
 */
public class DefaultClientDetailsService implements IClientDetailsService {

	protected static final Logger logger = LoggerFactory.getLogger(IClientDetailsService.class);

	protected static final PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

	/**
	 * accessToken有效时间
	 */
	protected int accessTokenValiditySeconds = 24 * 60 * 60;

	/**
	 * refreshToken有效时间
	 */
	protected int refreshTokenValiditySeconds = 24 * 60 * 60;

	/**
	 * 授权范围
	 */
	protected List<String> scopes = Arrays.asList("read", "write", "trust");

	/**
	 * 授权类型
	 */
	protected List<String> grantTypes = Arrays.asList("password", "refresh_token", "implicit", "client_credentials");

	/**
	 * 授权权限
	 */
	protected List<String> authorities = new ArrayList<>();

	@Override
	public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
		logger.debug("clientId.{}", clientId);
		BaseClientDetails clientDetails = new BaseClientDetails();
		clientDetails.setClientId(clientId);
		clientDetails.setClientSecret(passwordEncoder.encode(clientId));
		clientDetails.setAccessTokenValiditySeconds(this.accessTokenValiditySeconds);
		clientDetails.setRefreshTokenValiditySeconds(this.refreshTokenValiditySeconds);
		clientDetails.setScope(this.scopes);
		clientDetails.setAuthorizedGrantTypes(this.grantTypes);
		List<SimpleGrantedAuthority> authorities = new ArrayList<>();
		this.authorities.forEach(authority -> {
			authorities.add(new SimpleGrantedAuthority(authority));
		});
		clientDetails.setAuthorities(authorities);
		return clientDetails;
	}

}
